import pymysql

# 数据库连接配置
config = {
    'host': '192.168.14.93',
    'user': 'root',
    'password': 'abc123',
    'database': 'seal_system',
    'charset': 'utf8mb4'
}

# 数据
res = [
    {"board_temp": "38℃", "chip_temp": "39℃", "dev_get_sn": "7AIV02X2424000056", "dev_get_target": "BM1684X",
     "dev_id": 0, "dev_ip": "192.168.7.52", "id": 1, "mem_used_mem_total": "483MB/10515MB", "memory_usage_rate": "4.43%",
     "resource_num": 0, "tpu_util": "0.00%"},
    {"board_temp": "42℃", "chip_temp": "40℃", "dev_get_sn": "7AIV02X2424000056", "dev_get_target": "BM1684X",
     "dev_id": 1, "dev_ip": "192.168.7.52", "id": 2, "mem_used_mem_total": "0MB/10515MB", "memory_usage_rate": "0.00%",
     "resource_num": 0, "tpu_util": "0.00%"},
    {"board_temp": "40℃", "chip_temp": "38℃", "dev_get_sn": "7AIV02X2424000081", "dev_get_target": "BM1684X",
     "dev_id": 2, "dev_ip": "192.168.7.52", "id": 3, "mem_used_mem_total": "0MB/10515MB", "memory_usage_rate": "0.00%",
     "resource_num": 0, "tpu_util": "0.00%"},
    {"board_temp": "40℃", "chip_temp": "38℃", "dev_get_sn": "7AIV02X2424000081", "dev_get_target": "BM1684X",
     "dev_id": 3, "dev_ip": "192.168.7.52", "id": 4, "mem_used_mem_total": "0MB/10515MB", "memory_usage_rate": "0.00%",
     "resource_num": 2, "tpu_util": "0.00%"}
]

# SQL 插入语句
insert_query = """
    INSERT INTO t_resource_usage (id, dev_ip, dev_id, dev_get_target, dev_get_sn, board_temp, chip_temp, mem_used_mem_total, memory_usage_rate, tpu_util, resource_num)
    VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
    ON DUPLICATE KEY UPDATE
        dev_ip = VALUES(dev_ip),
        dev_id = VALUES(dev_id),
        dev_get_target = VALUES(dev_get_target),
        dev_get_sn = VALUES(dev_get_sn),
        board_temp = VALUES(board_temp),
        chip_temp = VALUES(chip_temp),
        mem_used_mem_total = VALUES(mem_used_mem_total),
        memory_usage_rate = VALUES(memory_usage_rate),
        tpu_util = VALUES(tpu_util),
        resource_num = VALUES(resource_num);
"""

# 写入数据库函数
def write_resource_usage(res):
    # 连接数据库
    conn = pymysql.connect(**config)
    cursor = conn.cursor()

    try:
        for record in res:
            # 提取值
            values = (
                record['id'], record['dev_ip'], record['dev_id'], record['dev_get_target'], record['dev_get_sn'],
                record['board_temp'], record['chip_temp'], record['mem_used_mem_total'], record['memory_usage_rate'],
                record['tpu_util'], record['resource_num']
            )
            # 执行插入语句
            cursor.execute(insert_query, values)

        # 提交事务
        conn.commit()
        print("数据插入成功！")

    except pymysql.MySQLError as e:
        print(f"数据库操作失败: {e}")
        conn.rollback()

    finally:
        cursor.close()
        conn.close()

# 调用写入函数
write_resource_usage(res)
